"use strict";

module.exports = app => {
  class CarouselGroupService extends app.Service {
    async create() {
      const { app, ctx } = this;
      const { CarouselGroup, Project, Admin, ProjectAdmin } =
        app.model.Tables.Web;

      const data = ctx.request.body;

      // 获取token
      // const token = ctx.get('authorization');
      // const adminRes = await Admin.findOne({
      //   where: {
      //     access_token: token,
      //   },
      // });
      // 根据token查找项目id
      // const projectRes = await ProjectAdmin.findOne({
      //   where: {
      //     adminId: adminRes.dataValues.id,
      //   },
      // });
      // console.log(projectRes);

      // 创建轮播图分组
      const res = await CarouselGroup.create({
        name: data.name,
        projectId: ctx.adminInfo.project_id,
        adminId: ctx.adminInfo.id,
      });
      return res;
    }

    async delete() {
      const { app, ctx } = this;
      const { CarouselGroup, Project, Admin, ProjectAdmin } =
        app.model.Tables.Web;

      // 删除
      const delRes = await CarouselGroup.destroy({
        where: {
          id: ctx.params.id,
          projectId: ctx.adminInfo.project_id,
        },
      });
      if (delRes) {
        return "删除成功";
      }
      return "id不存在,删除失败";
    }

    async update() {
      const { app, ctx } = this;
      const { CarouselGroup } = app.model.Tables.Web;
      const data = ctx.request.body;
      // 修改名称
      const res = await CarouselGroup.update(
        {
          name: data.name,
        },
        {
          where: {
            projectId: ctx.adminInfo.project_id,
            id: data.id,
          },
        }
      );
      if (res[0]) {
        return "修改成功";
      }
      return "id不存在,修改失败";
    }

    async get() {
      const { app, ctx } = this;
      const { CarouselGroup, Carousel } = app.model.Tables.Web;
      const data = ctx.query;

      const res = await CarouselGroup.findOne({
        where: {
          id: Number(data.carouselGroupId),
          projectId: data.projectId || ctx.adminInfo.project_id,
        },
        include: [{ model: Carousel, attributes: ["id", "url"] }],
      });

      return res;
    }

    async getAllCarouselGroup() {
      const { app, ctx } = this;
      const { CarouselGroup, Carousel } = app.model.Tables.Web;
      const data = ctx.query;

      // 查找全部轮播图分组下全部图片
      const res = await CarouselGroup.findAndCountAll({
        where: {
          projectId: data.projectId || ctx.adminInfo.project_id,
        },
        limit: Number(data.limit) || 10,
        offset: Number(data.offset) || 0,
        distinct: true,
        include: [{ model: Carousel }],
      });

      return res;
    }
  }
  return CarouselGroupService;
};
